package entity.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ：mmzs
 * @date ：Created in 2020/9/13 18:55
 * @description：
 * @modified By：
 * @version: $
 */
abstract public class AbstractFile implements LocalFile{

    //    一行的字符长度
    public double lineLength = 0;
    //    论文文本
    public String paperText = null;

    public String path;

    public File file;

    public int id;

    public String title;

    public String xmlFile;

    public String paperAbstract;

    public String keywords;

    public String authors;

    public String publish_year;

    public int index = 0;
//    //0：初始；1：正常；2：没有reference；3：参考文献没序号

    public AbstractFile() {
//        System.out.println("abstract");
    }

    abstract public String loadTextFromFile();

    public double countWordOneLine() {
        double result = - 1.0;
        try {
            FileReader fileReader = new FileReader(this.file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String s = bufferedReader.readLine();
            int i = 0;
            int sum = 0;
            ArrayList<Integer> lengthList = new ArrayList<>();
            while (s != null) {
                sum += s.length();
                i++;
                lengthList.add(s.length());
                s = bufferedReader.readLine();
            }
            double aver = lengthList.stream().mapToInt(a->a).summaryStatistics().getAverage();
            result = lengthList.stream().filter(a -> a > aver).mapToInt(a -> a).summaryStatistics().getAverage();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public String removeReference(String inputText) {
        String referencePattern = "\nReferences\n";
        Matcher m = Pattern.compile(referencePattern).matcher(inputText);
        if (m.find()) {
            inputText = inputText.substring(0, m.start());
        } else {
            System.out.println("找不到参考文献");
        }
        return inputText;
    }

    public int readLineAlong(String inputText, int startIndex) {
        int end = startIndex;
        if (inputText.charAt(end + 1) == '\n') {
            end++;
        }
        do {
            end++;
        } while (inputText.charAt(end) != '\n');
        return end + 1;
    }

    public int[] readLineCurrent(CharSequence inputText, int index) {
        int start = index;
        do {
            start--;
        } while (inputText.charAt(start) != '\n');
        int end = index;
        do {
            end++;
        } while (inputText.charAt(end) != '\n');
        int[] result = new int[2];
        result[0] = start + 1;
        result[1] = end + 1;
        return result;
    }

    public List<String> getReferenceFromLongText(String input) {
        //前面已经去掉页眉页脚
        List<String> result = new ArrayList<>();
        Matcher m = null;
        //哪一种类型的序号?
        int labelType = -1;
        int referenceType = -1;
        int label = 2;
        if (input.startsWith("1 ")) {
            //数字加空格
            labelType = 1;
        } else if (input.startsWith("1.")) {
            labelType = 2;
        } else if (input.startsWith("1")) {
            labelType = 3;
        } else if (input.startsWith("[1]")) {
            labelType = 4;
        } else {
            index = 3;
            return result;
        }

        //没有序号怎么办？没有序号就不用做了

        String leftPattern = null;
        String rightPattern = null;
        switch (labelType) {
            case 1:
                leftPattern = "\r\n *";
                rightPattern = " *";
                break;
            case 2:
                leftPattern = "\r\n *";
                rightPattern = "\\. *";
                break;
            case 3:
                leftPattern = "\r\n *";
                rightPattern = "";
                break;
            case 4:
                leftPattern = "\r\n *\\[";
                rightPattern = "\\] *";
                break;
            default:
                ;
        }

        m = Pattern.compile(leftPattern + label + rightPattern).matcher(input);
        m.find();

        do {
            int referenceEnd = m.start();
            String reference = input.substring(0, referenceEnd);

            result.add(reference);

            label++;
            input = input.substring(referenceEnd + 2);
            m = Pattern.compile(leftPattern + label + rightPattern).matcher(input);
        } while (m.find());

        //补上最后一条reference，最后一条到哪算完？连续两个/r/n算完
        boolean foundLastReference = false;
        String lastReference = "";
        do {
            m = Pattern.compile("\r\n").matcher(input);
            m.find();
            lastReference = lastReference.concat(input.substring(0, m.start()));
            input = input.substring(m.end());
            m = Pattern.compile("\\s*\r\n").matcher(input);
            if (m.lookingAt()) {
                foundLastReference = true;
            }
            if (input.trim().equals("")) {
                foundLastReference = true;
            }
        } while (!foundLastReference);
        result.add(lastReference);

        return result;
    }

    /**
     * create by: mmzs
     * description: 倒序读一行
     * create time: 2020/7/21 16:27
     *
     * @return
     * @Param: null
     */
    public int readLineReverse(CharSequence input, int endIndex) {
        int start = endIndex;
        if (input.charAt(start - 1) == '\n') {
            start--;
        }
        do {
            start--;
        } while (input.charAt(start) != '\n');
        return start + 1;
    }

    public void extractPaperAbstract() {
        String patterns = "\nAbstract";
        if (this.paperText.contains("Contents lists available at")) {
            String[] keywords = this.keywords.split(";");
            patterns = "\n" + keywords[keywords.length - 1];
        }
        Matcher m = Pattern.compile(patterns).matcher(this.paperText);
        if (m.find()) {
            int newLineStart = m.end();
            int newLineEnd = readLineAlong(paperText, newLineStart);
            StringBuilder stringBuilder = new StringBuilder();
            String newLineText = paperText.substring(newLineStart, newLineEnd);
            while (!newLineText.startsWith("1. ")) {
                stringBuilder.append(newLineText);
                newLineStart = newLineEnd;
                newLineEnd = readLineAlong(paperText, newLineStart);
                newLineText = paperText.substring(newLineStart, newLineEnd);
            }
            this.paperAbstract = stringBuilder.toString();
        }
    }

}
